<?php
class UpdateMaterialReceiptItemsAction extends CAction {
	public function run($id) {
		$model = $this->getController()->loadModel($id);
		if (!$model->isRecent && !Yii::app()->user->checkAccess('admin')) {
			throw new CHttpException(400, '一周之前创建的记录不可编辑');
		}
		$items = $model->items;
		$newItem = new MaterialReceiptItem();
		if (isset($_POST['MaterialReceiptItem'])) {
			foreach ($items as $i => $item) {
				if (isset($_POST['MaterialReceiptItem'][$i])) {
					$item->attributes = $_POST['MaterialReceiptItem'][$i];
					$item->save();
				}
			}
			//new item
			$i = count($items);
			if (isset($_POST['MaterialReceiptItem'][$i])) {
				$newItem->attributes = $_POST['MaterialReceiptItem'][$i];
				if ($newItem->validate()) {
					$newItem->materialReceiptId = $id;
					if ($newItem->save()) {
						$this->getController()
							->redirect(
								array(
									'updateItems',
									'id' => $id
								));
					}
				}
			}
			$model->save();
		}
		$this->getController()
			->render('updateItems', array(
				'model' => $model,
				'newItem' => $newItem
			));
	}
}
